package com.cqupt.utils;

import org.springframework.web.multipart.MultipartFile;

import javax.sound.sampled.*;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class AudioUtil {


    public static byte[] castToPcm(MultipartFile file) throws IOException {
        String fileType = getFileType(file.getInputStream());
        if (fileType.equalsIgnoreCase("pcm")) {
            // If already PCM, directly return the byte array
            return file.getBytes();
        } else if (fileType.equalsIgnoreCase("mp3")) {
            // If MP3, convert it to PCM and then return the byte array
            return convertMP3ToPCM(file.getInputStream());
        } else {
            throw new IllegalArgumentException("Unsupported file format. Only PCM or MP3 is supported.");
        }
    }


    private static String getFileType(InputStream inputStream) {
        AudioFileFormat fileFormat = null;
        try {
            fileFormat = AudioSystem.getAudioFileFormat(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (fileFormat != null) {
            return fileFormat.getType().getExtension();
        }
        return null;
    }


    private static byte[] convertMP3ToPCM(InputStream mp3InputStream) throws IOException {
        try (AudioInputStream in = AudioSystem.getAudioInputStream(mp3InputStream);
             ByteArrayOutputStream out = new ByteArrayOutputStream()) {
            AudioFormat baseFormat = in.getFormat();

            // Set output format to PCM
            AudioFormat targetFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, baseFormat.getSampleRate(),
                    16, baseFormat.getChannels(), baseFormat.getChannels() * 2, baseFormat.getSampleRate(), false);

            // Convert to PCM and write to ByteArrayOutputStream
            try (AudioInputStream pcmIn = AudioSystem.getAudioInputStream(targetFormat, in)) {
                byte[] buffer = new byte[8192];
                int bytesRead;
                while ((bytesRead = pcmIn.read(buffer)) != -1) {
                    out.write(buffer, 0, bytesRead);
                }
            }

            // Return the byte array
            return out.toByteArray();
        } catch (UnsupportedAudioFileException e) {
            e.printStackTrace();
            throw new IOException("Unsupported audio file format");
        }
    }
}
